package com.tticar.invmanager.tticar.controller;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.czy.tticar.dubbo.service.InvmanagerGoodsOrderService;
import com.tticar.invmanager.common.exception.MyServiceException;
import com.tticar.invmanager.common.shiro.LoginUser;
import com.tticar.invmanager.common.utils.MyResponseBody;
import com.tticar.invmanager.common.utils.ServiceUtil;
import com.tticar.invmanager.common.utils.date.DateStyle;
import com.tticar.invmanager.common.utils.date.DateUtil;
import com.tticar.invmanager.controller.BaseController;
import com.tticar.invmanager.entity.OutRepositoryDetail;
import com.tticar.invmanager.entity.vo.*;
import com.tticar.invmanager.mapper.MMaterielTticarMapper;
import com.tticar.invmanager.service.IOutRepositoryDetailService;
import com.tticar.invmanager.tticar.entity.DeliveryGoodsDTO;
import com.tticar.invmanager.tticar.entity.Store;
import com.tticar.invmanager.tticar.service.IGoodsOrderService;
import com.tticar.invmanager.tticar.service.IStoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import com.tticar.invmanager.tticar.entity.GoodsOrder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 产品订单表 前端控制器
 * </p>
 *
 * @author joeyYan
 * @since 2018-08-13
 */
@Controller
@RequestMapping("/tticar/goodsOrder")
public class GoodsOrderController extends BaseController {

    @Autowired
    private IGoodsOrderService goodsOrderService;

    @Autowired
    private InvmanagerGoodsOrderService invmanagerGoodsOrderService;

    @Autowired
    private IStoreService storeService;

    @Autowired
    private IStoreService tticarStoreService;

    @Autowired
    private IOutRepositoryDetailService outRepositoryService;

    @PostMapping
    @ResponseBody
    public MyResponseBody post(GoodsOrder goodsOrder) {
        goodsOrderService.insertOrUpdate(goodsOrder);
        return MyResponseBody.success();
    }

    /**
     * 修改订单 供应商优惠，运费
     * */
    @PostMapping("change")
    @ResponseBody
    public MyResponseBody change(@RequestParam("orderCode")Long orderCode,
                                 @RequestParam("changeMoney")BigDecimal changeMoney,
                                 @RequestParam("totalFee")BigDecimal totalFee,
                                 @RequestParam("sellStoreId")Long sellStoreId) {
        invmanagerGoodsOrderService.change(orderCode, changeMoney, totalFee, null, sellStoreId);
        return MyResponseBody.success();
    }

    @PostMapping("delete")
    @ResponseBody
    public MyResponseBody delete(@RequestParam("ids[]") List<Long> ids) {
        MyResponseBody responseBody = MyResponseBody.success();
        goodsOrderService.delete(ids);
        return responseBody;
    }

    /**
     * 接单/拒绝接单
     * */
    @PostMapping("receive")
    @ResponseBody
    public MyResponseBody receive(@RequestParam("orderId") Long id,@RequestParam("status") String status,
                                  @RequestParam("reason") String reason) {
        GoodsOrder goodsOrderDetail = goodsOrderService.selectById(id);
        MyResponseBody responseBody = MyResponseBody.success();
        invmanagerGoodsOrderService.confirmOrder(id,status,goodsOrderDetail.getSellStoreId(),reason);
        return responseBody;
    }

    /**
     * 拒绝接单填写理由页面
     * */
    @GetMapping("reject")
    public String rejectPage(@RequestParam("id") Long id,ModelMap modelMap) {
        GoodsOrder goodsOrderDetail = goodsOrderService.selectById(id);
        modelMap.put("goodsOrder", goodsOrderDetail);
        return "/tticar/goodsOrder/goodsOrder_reject";
    }


    @GetMapping("{id}")
    @ResponseBody
    public MyResponseBody get(@PathVariable("id") Long id) {
        MyResponseBody responseBody = MyResponseBody.success();
        responseBody.setData(goodsOrderService.selectById(id));
        return responseBody;
    }

    @GetMapping("edit")
    public String edit(GoodsOrder goodsOrder, ModelMap modelMap) {
        GoodsOrder goodsOrderDetail = goodsOrderService.selectById(goodsOrder.getId());
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String createTime = format.format(goodsOrderDetail.getCreatetime());
        modelMap.put("createTime",createTime );
        modelMap.put("goodsOrder", goodsOrderDetail);
        return "/tticar/goodsOrder/goodsOrder_update";
    }

    @GetMapping("delivery")
    public String delivery(GoodsOrder goodsOrder, ModelMap modelMap) {
        String orderCode = goodsOrder.getOrderCode();
        GoodsOrder goodsOrderDetail = goodsOrderService.selectById(Long.parseLong(orderCode));

//        List<SkuReturnToPage> skuReturnToPages = goodsOrderService.queryGoodsIdByOrderId(goodsOrderDetail.getId());
//        if (skuReturnToPages != null && skuReturnToPages.size() > 0) {
//            List<RelativeGoodsDTO> relativeGoodsDTOs = mMaterielTticarMapper.queryRelativeGoodsByTticarGoods(Long.valueOf(skuReturnToPages.get(0).getGoodsId()), skuReturnToPages.get(0).getSkuValue());
//            if (relativeGoodsDTOs != null && relativeGoodsDTOs.size() > 0) {
//                relativeGoodsDTOs.get(0).re
//            }
//        }

        modelMap.put("orderCode", orderCode);
        modelMap.put("sellStoreId", goodsOrderDetail.getSellStoreId());
        return "/tticar/goodsOrder/goodsOrder_delivery";
    }


    /**
     * 发货
     * */
    @PostMapping("deliverySubmit")
    @ResponseBody
    public MyResponseBody delivery(@RequestParam("orderId") Long id,@RequestParam("sellStoreId") Long sellStoreId,@RequestParam("rows") String rows) {
        MyResponseBody responseBody = MyResponseBody.success();
        List<DeliveryGoodsDTO> deliveryGoods  = JSONArray.parseArray(rows, DeliveryGoodsDTO.class);
        //仓储出库
        Wrapper wrapper = new EntityWrapper<>();
        wrapper.eq("busz_id", id);
        List<OutRepositoryDetail> outRepositoryDetails = outRepositoryService.selectList(wrapper);
        if (outRepositoryDetails != null && outRepositoryDetails.size() >0) {
            throw new MyServiceException("仓储已经出库，请勿重复发货");
        }

        outRepositoryService.deliveryGoods(deliveryGoods,id);
        //天天爱车发货  先取消天天爱车发货
//        invmanagerGoodsOrderService.delivery(id,sellStoreId);
        return responseBody;
    }


    @GetMapping("details")
    public String details(GoodsOrder goodsOrder, ModelMap modelMap) {
        GoodsOrder goodsOrderDetail = goodsOrderService.selectById(goodsOrder.getId());
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String createTime = format.format(goodsOrderDetail.getCreatetime());
        Store store = storeService.selectById(goodsOrderDetail.getStoreId());
        modelMap.put("storeName", store.getName());
        modelMap.put("goodsOrder", goodsOrderDetail);
        modelMap.put("totalMoney", goodsOrderDetail.getTotalMoney().toString());
        modelMap.put("realPayMoney", goodsOrderDetail.getRealPayMoney().toString());
        modelMap.put("createTime",createTime );
        return "/tticar/goodsOrder/goodsOrder_details";
    }

    @GetMapping("list/goods")
    @ResponseBody
    public List goodsList(String orderId) {
        return goodsOrderService.goodsListNew(orderId);
    }

    //临时数据
    @RequestMapping("list/goodsTmp")
    @ResponseBody
    public List goodsListTmp(String orderId) {
        return goodsOrderService.goodsList(orderId);

    }

    @GetMapping("list")
    @ResponseBody
    public Page list(MyPage<GoodsOrder> page, HttpServletRequest request, GoodsOrderSearchDTO goodsOrderSearchDTO) {
        Map<String, String[]> parameterMap = request.getParameterMap();
        Long sellStoreId = null;
        if (parameterMap.get("t.sellStoreId") != null) {
            String storeIdString = parameterMap.get("t.sellStoreId")[0];
            sellStoreId = Long.parseLong(storeIdString);
            goodsOrderSearchDTO.setSellStoreId(sellStoreId);
        } else if (goodsOrderSearchDTO.getSellStoreId() != null) {
            sellStoreId = goodsOrderSearchDTO.getSellStoreId();
        }
        if (sellStoreId == null) {
            List<Store> list = tticarStoreService.selectList();
            String sellStoreIdList = "(";
            for (int i=0; i<list.size(); i++) {
                sellStoreIdList = sellStoreIdList + list.get(i).getId() + ",";
            }
            sellStoreIdList = sellStoreIdList.substring(0, sellStoreIdList.length() - 1);
            sellStoreIdList = sellStoreIdList + ")";
            goodsOrderSearchDTO.setSellStoreIdList(sellStoreIdList);
        }

        Wrapper wrapper = getWrapper();
        return goodsOrderService.selectPage(wrapper, page,goodsOrderSearchDTO);
    }

    @GetMapping
    public String index(String searchText, ModelMap map) {
        map.put("searchText", searchText);
        //本月
        map.put("startTime", DateUtil.getMonthFirstDay(new Date()));
        map.put("endTime", DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD));
        return "/tticar/goodsOrder/goodsOrder";
    }

    /**
     * 供应商代门店下单页面
     */
    @GetMapping("placeOrderPage")
    public String placeOrderPage(ModelMap modelMap) {

        return "/tticar/goodsOrder/goodsOrder_placeOrder";
    }

}
